# encoding=utf-8

"""ParserTools:
    - 遵循设计模式，独立的工具代码
"""
import json
import os

import flask
from seg_system import ApplicationConfig


class ParserTools:
    @staticmethod
    def parser_redis_id_from_request(request: flask.Request):
        redis_id = request.form.get('redis_id', default='no_data')
        result = True
        if redis_id == 'no_data':
            result = False
        return redis_id, result

    @staticmethod
    def parser_img_name_from_request(request: flask.Request):
        img_name = request.form.get("img_name", default="")
        img_name = img_name.split(".")[0]
        img_name = img_name + ".png"
        return img_name

    @staticmethod
    def parser_name_token_from_request(request: flask.Request):
        user_name = request.form.get("user_name", default=None)
        token = request.form.get('token', default=None)
        return user_name, token

    @staticmethod
    def parser_download_param_from_request(request: flask.Request):
        language = request.form.get("language", default="ENG")
        user_name, token = ParserTools.parser_name_token_from_request(request)
        return user_name, token, language

    @staticmethod
    def parser_config_from_upload_json(request: flask.Request):
        data = request.form.get('data', default="")
        if data == "":
            return {
                'result': False,
                'message': 'json is empty'
            }

        data = json.loads(data)

        enhance_choice = data['enhance_choice']
        enhance_model = ApplicationConfig.NetConfig.ENHANCE_DICT[enhance_choice]

        segmentation_choice = data['segmentation_choice']
        segmentation_model = ApplicationConfig.NetConfig.SEGMENTATION_DICT[segmentation_choice]

        grade_choice = data['grade_choice']
        grade_model = ApplicationConfig.NetConfig.GRADE_DICT[grade_choice]

        vascular_choice = data['vascular_choice']
        vascular_model = ApplicationConfig.NetConfig.GRADE_DICT[vascular_choice]

        return {
            'enhance': [enhance_choice, enhance_model],
            'segmentation': [segmentation_choice, segmentation_model],
            'grade': [grade_choice, grade_model],
            'vascular': [vascular_choice, vascular_model]
        }

    @staticmethod
    def parser_from_file_to_url(file_path, url_path):
        if os.path.exists(file_path):
            return url_path
        return ""

    @staticmethod
    def parser_from_file_to_str(file_path):
        if os.path.exists(file_path):
            with open(file_path) as temp_file:
                line = temp_file.readline()
                t_str = line.strip()
                return t_str
        else:
            return ""

    @staticmethod
    def parse_from_image_name(img_name: str, saver, saver_with_path, **kwargs):
        """
            image_name: 图片名称
            saver: 相对路径对象，用于创建URL
            saver_with_path: 绝对路径，用于判断文件是否存在
        """
        d = {}
        d['segmentation'] = ParserTools.parser_from_segmentation(img_name, saver, saver_with_path)

        vascular_saver = kwargs.get('vascular_saver')
        vascular_saver_with_path = kwargs.get('vascular_saver_with_path')
        d['vascular'] = ParserTools.parser_from_vascular(img_name, vascular_saver, vascular_saver_with_path)
        return d

    @staticmethod
    def parser_from_segmentation(img_name, saver, saver_with_path):
        d = {}
        if not os.path.exists(saver_with_path.NORMAL_0):
            d['result'] = False
            d['message'] = "user haven't upload, or token has change"

        IP_PORT = 'http://' + ApplicationConfig.URLConfig.BASE_URL + ":" + ApplicationConfig.URLConfig.BASE_PORT

        # for f0
        f0_0 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.NORMAL_0, img_name), os.path.join(IP_PORT, saver.NORMAL_0, img_name)
        )
        f0_1 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.ENHANCE_0, img_name), os.path.join(IP_PORT, saver.ENHANCE_0, img_name)
        )
        # 注意这里需求变更，需要把分割图像和原图合并，因此存到临时目录下
        f1_1 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.NORMAL_TMP, img_name), os.path.join(IP_PORT, saver.NORMAL_TMP, img_name)
        )
        f1_2 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.ENHANCE_TMP, img_name), os.path.join(IP_PORT, saver.ENHANCE_TMP, img_name)
        )
        f2_1 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.NORMAL_2, img_name), os.path.join(IP_PORT, saver.NORMAL_2, img_name)
        )
        f2_2 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.ENHANCE_2, img_name), os.path.join(IP_PORT, saver.ENHANCE_2, img_name)
        )
        d['f0'] = [f0_0, f0_1]
        d['f1'] = [f1_1, f1_2]
        d['f2'] = [f2_1, f2_2]

        t2_1, t2_2 = os.path.join(saver_with_path.NORMAL_2_1, img_name), os.path.join(saver_with_path.ENHANCE_2_1,
                                                                                      img_name)
        t2_1_str = ParserTools.parser_from_file_to_str(t2_1 + ".txt")
        t2_2_str = ParserTools.parser_from_file_to_str(t2_2 + ".txt")

        d['f2_1'] = [t2_1_str, t2_2_str]

        f3_0 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.NORMAL_3, img_name), os.path.join(IP_PORT, saver.NORMAL_3, img_name)
        )
        f3_1 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.ENHANCE_3, img_name), os.path.join(IP_PORT, saver.ENHANCE_3, img_name)
        )
        d['f3'] = [f3_0, f3_1]

        d['result'] = True
        d['message'] = 'image has founded'
        return d

    @staticmethod
    def parser_from_vascular(img_name: str, saver, saver_with_path):
        d = {}

        if not os.path.exists(saver_with_path.NORMAL_0):
            d['result'] = False
            d['message'] = "user haven't upload, or token has change"

        IP_PORT = 'http://' + ApplicationConfig.URLConfig.BASE_URL + ":" + ApplicationConfig.URLConfig.BASE_PORT

        # for f0
        f0_0 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.NORMAL_0, img_name), os.path.join(IP_PORT, saver.NORMAL_0, img_name)
        )
        f0_1 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.ENHANCE_0, img_name), os.path.join(IP_PORT, saver.ENHANCE_0, img_name)
        )
        f1_1 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.NORMAL_1_0, img_name), os.path.join(IP_PORT, saver.NORMAL_1_0, img_name)
        )
        f1_2 = ParserTools.parser_from_file_to_url(
            os.path.join(saver_with_path.ENHANCE_1_0, img_name), os.path.join(IP_PORT, saver.ENHANCE_1_0, img_name)
        )
        if not ApplicationConfig.SystemConfig.USE_MATPLOTLIB_TXT:
            f2_1 = ParserTools.parser_from_file_to_url(
                os.path.join(saver_with_path.NORMAL_2, img_name), os.path.join(IP_PORT, saver.NORMAL_2, img_name)
            )
            f2_2 = ParserTools.parser_from_file_to_url(
                os.path.join(saver_with_path.ENHANCE_2, img_name), os.path.join(IP_PORT, saver.ENHANCE_2, img_name)
            )
        else:
            t_f2_1, t_f2_2 = os.path.join(saver_with_path.NORMAL_2, img_name), os.path.join(saver_with_path.ENHANCE_2,
                                                                                            img_name)
            f2_1 = ParserTools.parser_from_file_to_str(t_f2_1 + ".txt")
            f2_2 = ParserTools.parser_from_file_to_str(t_f2_2 + ".txt")
        d['f0'] = [f0_0, f0_1]
        d['f1'] = [f1_1, f1_2]
        d['f2'] = [f2_1, f2_2]

        t2_1, t2_2 = os.path.join(saver_with_path.NORMAL_3, img_name), os.path.join(saver_with_path.ENHANCE_3,
                                                                                    img_name)
        t2_1_str = ParserTools.parser_from_file_to_str(t2_1 + ".txt")
        t2_2_str = ParserTools.parser_from_file_to_str(t2_2 + ".txt")

        d['f2_1'] = [t2_1_str, t2_2_str]

        d['result'] = True
        d['message'] = 'image has founded'
        return d
